const Router = require('koa-router')
const { Product, ProductCategory, Inventory } = require('../models')
const auth = require('../middleware/auth')
const { Op } = require('sequelize')

const router = new Router({ prefix: '/api' })

// 获取产品列表
router.get('/products', auth.requirePermission('product:read'), async (ctx) => {
  try {
    const {
      current = 1,
      pageSize = 10,
      search = '',
      category_id,
      status,
      sort = 'created_at',
      order = 'DESC'
    } = ctx.query

    const page = parseInt(current)
    const size = parseInt(pageSize)
    const offset = (page - 1) * size
    const where = {}

    // 搜索条件
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { sku: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ]
    }

    if (category_id) {
      where.category_id = category_id
    }

    if (status !== undefined) {
      where.status = status
    }

    const { count, rows } = await Product.findAndCountAll({
      where,
      include: [
        {
          model: ProductCategory,
          as: 'category',
          attributes: ['id', 'name', 'code']
        },
        {
          model: Inventory,
          as: 'inventory',
          attributes: ['id', 'quantity', 'reserved_quantity', 'min_stock', 'max_stock']
        }
      ],
      order: [[sort, order.toUpperCase()]],
      limit: size,
      offset
    })

    ctx.body = {
      code: 200,
      message: '获取产品列表成功',
      data: {
        list: rows,
        total: count,
        page,
        size
      }
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ctx.body = {
      code: 500,
      message: '获取产品列表失败',
      error: error.message
    }
  }
})

// 获取产品详情
router.get('/products/:id', auth.requirePermission('product:read'), async (ctx) => {
  try {
    const { id } = ctx.params

    const product = await Product.findByPk(id, {
      include: [
        {
          model: ProductCategory,
          as: 'category',
          attributes: ['id', 'name', 'code']
        },
        {
          model: Inventory,
          as: 'inventory',
          attributes: ['id', 'quantity', 'reserved_quantity', 'min_stock', 'max_stock']
        }
      ]
    })

    if (!product) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '产品不存在'
      }
      return
    }

    ctx.body = {
      code: 200,
      message: '获取产品详情成功',
      data: product
    }
  } catch (error) {
    console.error('获取产品详情失败:', error)
    ctx.body = {
      code: 500,
      message: '获取产品详情失败',
      error: error.message
    }
  }
})

// 创建产品
router.post('/products', auth.requirePermission('product:create'), async (ctx) => {
  try {
    const {
      name,
      sku,
      description,
      category_id,
      price,
      cost,
      unit,
      weight,
      dimensions,
      images,
      attributes,
      tags,
      status = 'active',
      is_featured = false,
      min_stock = 0,
      max_stock = null
    } = ctx.request.body

    // 验证必填字段
    if (!name || !sku || !category_id) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '产品名称、SKU和分类为必填项'
      }
      return
    }

    // 检查SKU是否已存在
    const existingSku = await Product.findOne({ where: { sku } })
    if (existingSku) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: 'SKU已存在'
      }
      return
    }

    // 验证分类是否存在
    const category = await ProductCategory.findByPk(category_id)
    if (!category) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '产品分类不存在'
      }
      return
    }

    const product = await Product.create({
      name,
      sku,
      description,
      category_id,
      price: parseFloat(price) || 0,
      cost: parseFloat(cost) || 0,
      unit: unit || '个',
      weight: weight ? parseFloat(weight) : null,
      dimensions,
      images,
      attributes,
      tags,
      status,
      is_featured,
      min_stock: parseInt(min_stock) || 0,
      max_stock: max_stock ? parseInt(max_stock) : null,
      created_by: ctx.user.id
    })

    // 创建对应的库存记录
    await Inventory.create({
      product_id: product.id,
      quantity: 0,
      reserved_quantity: 0,
      min_stock: parseInt(min_stock) || 0,
      max_stock: max_stock ? parseInt(max_stock) : null
    })

    ctx.body = {
      code: 200,
      message: '创建产品成功',
      data: product
    }
  } catch (error) {
    console.error('创建产品失败:', error)
    ctx.body = {
      code: 500,
      message: '创建产品失败',
      error: error.message
    }
  }
})

// 更新产品
// 更新产品
router.put('/products/:id', auth.requirePermission('product:update'), async (ctx) => {
  try {
    const { id } = ctx.params
    const {
      name,
      sku,
      description,
      category_id,
      price,
      cost,
      unit,
      weight,
      dimensions,
      images,
      attributes,
      tags,
      status,
      is_featured,
      min_stock,
      max_stock
    } = ctx.request.body

    const product = await Product.findByPk(id)
    if (!product) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '产品不存在'
      }
      return
    }

    // 如果更新SKU，检查新SKU是否已存在
    if (sku && sku !== product.sku) {
      const existingSku = await Product.findOne({ where: { sku } })
      if (existingSku) {
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: 'SKU已存在'
        }
        return
      }
    }

    // 如果更新分类，验证分类是否存在
    if (category_id && category_id !== product.category_id) {
      const category = await ProductCategory.findByPk(category_id)
      if (!category) {
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: '产品分类不存在'
        }
        return
      }
    }

    const updateData = {}
    if (name !== undefined) updateData.name = name
    if (sku !== undefined) updateData.sku = sku
    if (description !== undefined) updateData.description = description
    if (category_id !== undefined) updateData.category_id = category_id
    if (price !== undefined) updateData.price = parseFloat(price)
    if (cost !== undefined) updateData.cost = parseFloat(cost)
    if (unit !== undefined) updateData.unit = unit
    if (weight !== undefined) updateData.weight = weight ? parseFloat(weight) : null
    if (dimensions !== undefined) updateData.dimensions = dimensions
    if (images !== undefined) updateData.images = images
    if (attributes !== undefined) updateData.attributes = attributes
    if (tags !== undefined) updateData.tags = tags
    if (status !== undefined) updateData.status = status
    if (is_featured !== undefined) updateData.is_featured = is_featured
    if (min_stock !== undefined) updateData.min_stock = parseInt(min_stock) || 0
    if (max_stock !== undefined) updateData.max_stock = max_stock ? parseInt(max_stock) : null

    await product.update(updateData)

    // 同步更新库存表的最大最小库存
    if (min_stock !== undefined || max_stock !== undefined) {
      const inventory = await Inventory.findOne({ where: { product_id: id } })
      if (inventory) {
        const inventoryUpdate = {}
        if (min_stock !== undefined) inventoryUpdate.min_stock = parseInt(min_stock) || 0
        if (max_stock !== undefined) inventoryUpdate.max_stock = max_stock ? parseInt(max_stock) : null
        await inventory.update(inventoryUpdate)
      }
    }

    ctx.body = {
      code: 200,
      message: '更新产品成功',
      data: product
    }
  } catch (error) {
    console.error('更新产品失败:', error)
    ctx.body = {
      code: 500,
      message: '更新产品失败',
      error: error.message
    }
  }
})

// 删除产品
// 删除产品
router.delete('/products/:id', auth.requirePermission('product:delete'), async (ctx) => {
  try {
    const { id } = ctx.params

    const product = await Product.findByPk(id)
    if (!product) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '产品不存在'
      }
      return
    }

    // 检查是否有关联的库存记录
    const inventory = await Inventory.findOne({ where: { product_id: id } })
    if (inventory && inventory.quantity > 0) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '该产品还有库存，无法删除'
      }
      return
    }

    // 删除库存记录
    if (inventory) {
      await inventory.destroy()
    }

    await product.destroy()

    ctx.body = {
      code: 200,
      message: '删除产品成功'
    }
  } catch (error) {
    console.error('删除产品失败:', error)
    ctx.body = {
      code: 500,
      message: '删除产品失败',
      error: error.message
    }
  }
})

// 获取产品分类列表
router.get('/categories/list', auth.requirePermission('product:read'), async (ctx) => {
  try {
    const categories = await ProductCategory.findAll({
      order: [['created_at', 'DESC']],
      include: [
        {
          model: Product,
          as: 'products',
          attributes: ['id'],
          required: false
        }
      ]
    })

    // 添加产品数量统计
    const categoriesWithCount = categories.map(category => ({
      ...category.toJSON(),
      product_count: category.products ? category.products.length : 0
    }))

    ctx.body = {
      code: 200,
      message: '获取产品分类列表成功',
      data: categoriesWithCount
    }
  } catch (error) {
    console.error('获取产品分类列表失败:', error)
    ctx.body = {
      code: 500,
      message: '获取产品分类列表失败',
      error: error.message
    }
  }
})

// 创建产品分类
router.post('/categories', auth.requirePermission('product:create'), async (ctx) => {
  try {
    const { name, code, description, status = 1 } = ctx.request.body

    if (!name || !code) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '分类名称和编码为必填项'
      }
      return
    }

    // 检查编码是否已存在
    const existingCode = await ProductCategory.findOne({ where: { code } })
    if (existingCode) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '分类编码已存在'
      }
      return
    }

    const category = await ProductCategory.create({
      name,
      code,
      description,
      status
    })

    ctx.body = {
      code: 200,
      message: '创建产品分类成功',
      data: category
    }
  } catch (error) {
    console.error('创建产品分类失败:', error)
    ctx.body = {
      code: 500,
      message: '创建产品分类失败',
      error: error.message
    }
  }
})

module.exports = router